package com.sdy.supermarket.web.controller;

import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.controller.BaseController;
import com.sdy.supermarket.biz.model.FileUploadRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * function：
 * created by Snaky on 2019-07-18 10:43
 **/

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController extends BaseController {
    @Autowired
    private FsApi fsApi;
    /**
     * 文件上传
     */
    @PostMapping("/uploadOne")
    public Response upload(@RequestPart("file") MultipartFile file) throws Exception {
        String type = "supermarket";
        byte[] bt = file.getBytes();
        FileObj fileObj = fsApi.uploadFile(ArrayUtils.toObject(bt), file.getOriginalFilename(), type);
        return Response.success(fileObj);
    }

    /**
     * 多文件上传--
     *
     * @param files 文件数组
     * @param type  文件类型、文件标记
     * @return Response
     */
    @PostMapping("/upload")
    public Response update(@RequestParam("files") MultipartFile[] files, String type) throws IOException {
        if (files == null || files.length == 0) {
            return Response.error("文件为空");
        }
        List<FileUploadRes> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String url = fsApi.upload(ArrayUtils.toObject(file.getBytes()), file.getOriginalFilename(), type).getData();
            list.add(new FileUploadRes()
                    .setFileName(file.getOriginalFilename())
                    .setPath(url)
                    .setType(type)
                    .setSuccess(true)
            );
        }
        return Response.success(list);
    }
}
